﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Driver.Builders;

namespace MidasPoster
{
    public class AutoIndexManager
    {
        private MongoCollection<BsonDocument> m_IndexDocument = null ;


        public AutoIndexManager(ref MongoCollection<BsonDocument> _BsonDocument)
        {
            m_IndexDocument = _BsonDocument;
        }
        public int GetNewIndex(EDBINFOS eDBName)
        {
            int iCurIndex = 0;
            QueryDocument query = new QueryDocument("INDEXNAME", eDBName.GetDescription());
            BsonDocument docFind = m_IndexDocument.FindOneAs<BsonDocument>(query);
            if (docFind != null)
            {

                    iCurIndex = docFind["INDEXVALUE"].ToInt32();
                    iCurIndex++;

                    UpdateDocument update = new UpdateDocument { { "$set", new BsonDocument("INDEXVALUE", iCurIndex) } };
                    query = new QueryDocument("_id", docFind["_id"]);
                    m_IndexDocument.Update(query, update);
                    

            }
            else
            {
                iCurIndex++;
                MDTB_KEYINDEX _keyindex = new MDTB_KEYINDEX();
                _keyindex.INDEXNAME = eDBName.GetDescription();
                _keyindex.INDEXVALUE = iCurIndex;
                BsonDocument bd = BsonExtensionMethods.ToBsonDocument(_keyindex);
                m_IndexDocument.Insert(bd);

            }


            return iCurIndex;
        }
        
        
    }
}
